<?php

namespace App\Console\Commands;

use App\OrderPay;
use App\Repositories\DistributeRepository;
use App\Repositories\OrderRespository;
use App\User;
use App\UserLeader;
use Carbon\Carbon;
use Illuminate\Console\Command;

class DistributeCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    //修正绑定关系
    protected $signature = 'distribute:user';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '修正绑定关系，将绑定关系存在 关注公众号但未有关系的绑定';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        \DB::transaction(function () {
            UserLeader::where('created_at', '>', Carbon::yesterday())->chunk(100, function ($userLeader) {
                foreach ($userLeader as $v) {
                    $app = \EasyWeChat::officialAccount();
                    $user = User::find($v->user_id);
                    if (!$user) {
                        return false;
                    }
                    $result = $app->user->get(User::find($v->user_id)->openid);
                    if (isset($result['subscribe']) && $result['subscribe'] == 1) {
                        if ($user->team_leader != $v->leader_id) {
                            //   print_r($user->id.'\n');
                            \Log::error('绑定关系人',$user->toArray());
                            //绑定关系
                            $distribute = new  DistributeRepository();
                            $distribute->bindDistribute($user, $v->leader_id);
                            $orderPay = OrderPay::where('pay_status', 1)->where('refund_status', '!=', OrderPay::REFUND_STATUS_APPLIED)->where('user_id', $user->id)->get();
                            foreach ($orderPay as $v) {
                                $order = new OrderRespository();
                                $user = User::find($v->user_id);
                                $order->teamHandle($user, $v);
                            }

                        }
                    }

                }
            });
        });
    }
}
